package com.atguigu.srb.oss.controller;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author zwj
 * @create 2021-10-12 16:38
 */
@RequestMapping("api/oss/file")
@RestController
//@CrossOrigin
@Api(tags = "阿里云文件管理")
@Slf4j
public class FileController {
    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    @ApiOperation("oss上传文件")
    public R upload(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file")MultipartFile file,
            @ApiParam(value = "模块",required = true)
            @RequestParam("module") String module){
        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String url = fileService.upload(inputStream, module, filename);
            log.info("文件上传成功");
            return R.ok().data("url",url);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @DeleteMapping("/remove")
    @ApiOperation("oss文件删除")
    public R remove(
            @ApiParam(value = "删除的文件url",required = true)
            @RequestParam("url") String url){
        fileService.remove(url);
        log.info("oss文件删除成功");
        return R.ok().message("文件删除成功");
    }
}
